package com.dyy.AI_System.service.impl;

import com.dyy.AI_System.domain.dto.LoginRequest;
import com.dyy.AI_System.domain.po.Users;
import com.dyy.AI_System.domain.vo.LoginResponse;
import com.dyy.AI_System.mapper.UsersMapper;
import com.dyy.AI_System.service.IUsersService;
import com.dyy.AI_System.utils.JwtUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dyy
 * @since 2025-10-13
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private JwtUtil jwtUtil;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public Users getByUsername(String username) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<Users> pageQuery(Integer pageNum, Integer pageSize, String keyword) {
        Page<Users> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Users::getUsername, keyword)
                    .or().like(Users::getName, keyword)
                    .or().like(Users::getEmail, keyword)
                    .or().like(Users::getPhone, keyword);
        }
        
        // 按创建时间降序排列
        queryWrapper.orderByDesc(Users::getCreatedAt);
        
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Users> getByDepartmentId(Long departmentId) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getDepartmentId, departmentId)
                .eq(Users::getIsActive, true); // 只查询激活的用户
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public boolean updateStatus(Long id, Boolean isActive) {
        Users user = new Users();
        user.setId(id);
        user.setIsActive(isActive);
        user.setUpdatedAt(LocalDateTime.now());
        return updateById(user);
    }

    // 重写save方法，添加创建和更新时间
    @Override
    public boolean save(Users entity) {
        entity.setCreatedAt(LocalDateTime.now());
        entity.setUpdatedAt(LocalDateTime.now());
        return super.save(entity);
    }

    // 重写updateById方法，更新更新时间
    @Override
    public boolean updateById(Users entity) {
        entity.setUpdatedAt(LocalDateTime.now());
        return super.updateById(entity);
    }

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 根据用户名查询用户
        Users user = getByUsername(loginRequest.getUsername());
        
        // 验证用户是否存在、是否激活
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        if (!user.getIsActive()) {
            throw new RuntimeException("账户已被禁用，请联系管理员");
        }
        
        // 验证密码
        if (!verifyPassword(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user);
        
        // 更新最后登录时间
        user.setLastLoginAt(LocalDateTime.now());
        updateById(user);
        
        // 构建登录响应
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        
        // 构建用户信息
        LoginResponse.LoginUser loginUser = new LoginResponse.LoginUser();
        loginUser.setId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setName(user.getName());
        loginUser.setEmail(user.getEmail());
        loginUser.setRole(user.getRole());
        
        loginResponse.setUser(loginUser);
        
        return loginResponse;
    }

    @Override
    public boolean verifyPassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    @Override
    public String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }
}
